/*
 @coding  : utf-8
 @Time    : 2023/5/22 17:28
 @Author  : Rumou
 @File    : 20230522-链表反转.go
 @Description:
*/

package main

import "fmt"

// Node 定义节点结构体
type Node struct {
	data int
	next *Node
}

// LinkedList 定义链表结构体
type LinkedList struct {
	head *Node
}

// Add 增加链表节点元素
func (list *LinkedList) Add(value int) {
	newNode := &Node{data: value}
	if list.head == nil {
		list.head = newNode
	} else {
		currentNode := list.head
		for currentNode.next != nil {
			currentNode = currentNode.next
		}
		currentNode.next = newNode
	}
}

// Print 输出链表
func (list *LinkedList) Print() {
	currentNode := list.head
	for currentNode != nil {
		if currentNode.next != nil {
			fmt.Printf("%v -> ", currentNode.data)
		} else {
			fmt.Printf("%v", currentNode.data)
		}
		currentNode = currentNode.next
	}
	fmt.Println()
}

// Reverse 链表反转
func (list *LinkedList) Reverse() {
	var prevNode *Node
	currentNode := list.head
	for currentNode != nil {
		nextNode := currentNode.next
		currentNode.next = prevNode
		prevNode = currentNode
		currentNode = nextNode
	}
	list.head = prevNode
}

func main() {
	list := &LinkedList{}
	list.Add(1)
	list.Add(2)
	list.Add(3)

	fmt.Println("链表：")
	list.Print()
	
	list.Reverse()
	fmt.Println("反转链表：")
	list.Print()
}
